<template>
  <div class="wrap">
    <TagState v-model:value="status" :config="config" :tag-name-styles="{fontSize: '32rpx'}" line />
    <TagState v-if="status !== 'wait' && status !== 'expired'" v-model:value="waitState" :config="waitConfig" />
    <div v-if="status === 'wait' || status === 'expired'" class="search_input">
      <u-search v-model="searchVal" :input-style="{height: '72rpx'}" :show-action="false" placeholder="请输入合同名称/合同编号/发起方名称" />
    </div>
    <div class="list">
      <AutoList ref="SignRef" :params="{ state: paramsStatus, key: searchVal, signStatus: signTypeStatus, signStatus1: signTypeStatus1 }" :request="getData" @list="signList = $event">
        <div
          v-for="(d, index) in signList"
          :key="index"
          class="sign_box"
        >
          <div class="contractName">
            <span>{{ d.contractName }}</span>
            <span :style="{color: signStatus[d?.signState?.toString()]?.color}">{{ signStatus[d?.signState?.toString()]?.label }}</span>
          </div>
          <div class="contractNo">
            <div class="color">合同编号：</div>
            <div>{{ d.contractNo }}</div>
          </div>
          <div
            v-if="status === 'wait' || (status === 'success' && waitState !== 'person') || (status === 'reject' && waitState !== 'person') || status === 'expired'"
            class="contractNo"
          >
            <div class="color">发起方：</div>
            <div>{{ d.companyName }}</div>
          </div>
          <div class="contractNo">
            <div class="color">发起时间：</div>
            <div>{{ d.publishDate }}</div>
          </div>
          <template v-if="status === 'success'">
            <div class="contractNo">
              <div class="color">通过时间：</div>
              <div>{{ d?.enterpriseSignFinishDate }}</div>
            </div>
          </template>
          <template v-if="status === 'reject' && waitState !== 'otherMainBody'">
            <div class="contractNo">
              <div class="color">驳回时间:</div>
              <div>{{ d?.rejectTime }}</div>
            </div>
          </template>
          <template v-if="status === 'reject' && waitState !== 'otherMainBody'">
            <div class="reject_reason">
              <div class="color">驳回理由:</div>
              <div v-if="d.rejectReason?.length < 16">
                <div style="text-align: right">{{ d.rejectReason }}</div>
              </div>
              <div v-else :class="isExpand ? '' : 'flex_cen_cen'" @tap="isExpand = true">
                <div :class="isExpand ? '' : 'textLineHidden'" :style="{width: isExpand ? '400rpx' : '380rpx'}">{{ d.rejectReason }}</div>
                <div v-if="isExpand" class="flex_end" style="width: 400rpx;" @tap.stop="isExpand = false">
                  <u-icon name="arrow-up-fill" size="12" />
                  <span style="margin-left: 6rpx">收起</span>
                </div>
                <u-icon v-if="!isExpand" name="arrow-down-fill" size="12" />
              </div>
            </div>
          </template>
          <template v-if="status === 'expired'">
            <div class="contractNo">
              <div class="color">失效时间：</div>
              <div>{{ d?.expiredTime }}</div>
            </div>
          </template>
          <div class="handle" style="text-align: right">
            <Button v-if="status !== 'wait'" type="solid" @confirm="view(status === 'expired' ? d.contractPath : d.signViewPath)">预览</Button>
            <div v-if="status === 'wait'" style="width: 30rpx; display: inline-block" />
            <Button v-if="status === 'wait'" @confirm="sign(d.id)">立即签约</Button>
          </div>
        </div>
      </AutoList>
    </div>
  </div>
  <!--电子合同签约服务 弹框  -->
  <up-popup v-model:show="showPrivacy" mode="bottom" round="40">
    <div class="pricacyPop">
      <div class="title">授权提醒</div>
      <div class="tips">电子合同签约服务由我们的授权合作伙伴深圳法大大网络科技有限公司(“法大大”)提供。为提供该服务，您同意我们将您的个人信息(姓名、身份证号码、电话号码)共亨给授权合作伙伴。</div>
      <div class="options">
        <div class="firstPrav">
          <up-checkbox v-model:checked="aloneChecked1" active-color="#1890FF" used-alone @change="changePrivacy1" />
          <div class="rightItem">
            <div class="fchkb">
              我已仔细阅读并同意第三方相关隐私政策(请长按复制网址
              <span class="schkb" @tap.stop="copyToClipboard({
                content: 'https://agreement-os1.fadada.com/46d9beae63024d469cb971ce5757978a',
                successTip: '链接复制成功,请前往浏览器打开',
                failTip: '链接复制失败',
              })"
              >https://agreement-os1.fadada.com/46d9beae63024d469cb971ce5757978a</span>
              至浏览器访问第三方隐私政策)。
            </div>
          </div>
        </div>
        <div class="secondPrav">
          <up-checkbox v-model:checked="aloneChecked2" active-color="#1890FF" used-alone @change="changePrivacy2" /><div class="rightInfo">我同意将我的个人信息共亨给第三方。</div>
        </div>
      </div>
      <div class="line" />
      <div class="foot">
        <Button :styles="{ width:'300rpx',height:'70rpx' }" size="M" type="solid" @confirm="cancelPop">取消</Button>
        <Button :disabled="!(aloneChecked1 && aloneChecked2)" :styles="{ width:'300rpx',height:'70rpx' }" size="M" @confirm="agPop">同意</Button>
      </div>
    </div>
  </up-popup>
</template>

<script lang="ts" setup>
import { computed, ref } from 'vue'
import AutoList from '@C/AutoList.vue'
import TagState from '@C/TagState.vue'
import { MsgLoading, MsgLoadingClear } from '@C/Msg'
import { onShow, Router, LStorage, copyToClipboard, storeCommit } from '@U/common'
import Button from '@C/Button.vue'
import {
  getCoopAgreementList,
  signContract,
  getPersonSignList,
  getStudioSignList,
  getThirdEnterpriseSignList,
} from '@P/Sign/request'
import type { IFunc, IObj, IObjArray } from '@/interface'

// 驳回理由相关
const isExpand = ref(false)
const searchVal = ref('')
const status = ref('wait')
const waitState = ref('person')
const signHandler = () => {
  let api
  if (status.value === 'wait') api = getCoopAgreementList
  if (status.value === 'success' || status.value === 'reject') {
    if (waitState.value === 'person') api = getPersonSignList
    if (waitState.value === 'studio') api = getStudioSignList
    if (waitState.value === 'otherMainBody') api = getThirdEnterpriseSignList
  }
  if (status.value === 'expired') api = getCoopAgreementList
  return api
}
const getData = async (e: IObj) => (signHandler as IFunc)()(e)

onShow(() => {
  FDDElectronicSigningService()
  const { defSignStatusTagKey = '' } = Router.route().params
  if (defSignStatusTagKey) {
    // 加单次定时器，解决其他页面跳转过来时不显示数据
    setTimeout(() => {
      status.value = defSignStatusTagKey
    }, 1000)
  }
  if (Router.route().params?.tab) {
    const tab = Router.route().params?.tab
    // 加单次定时器，解决其他页面跳转过来时不显示数据
    setTimeout(() => {
      status.value = tab || 'wait'
    }, 1000)
  }
})

const SignRef = ref()
const config = ref([
  { label: '待签约', key: 'wait', dot: false },
  { label: '已签约', key: 'success' },
  { label: '被驳回', key: 'reject' },
  { label: '已失效', key: 'expired' },
])
const waitConfig = ref([
  { label: '合作申请书', key: 'person', dot: false },
  { label: '工作室签约', key: 'studio', dot: false },
  { label: '其他主体签约', key: 'otherMainBody', dot: false },
])

const paramsStatus = computed(() => ['wait', 'success', 'reject', 'expired'].indexOf(status.value))
const signTypeStatus1 = computed(() => ['person', 'studio', 'otherMainBody'].indexOf(waitState.value))
const signTypeStatus = computed(() => (status.value === 'success' ? '2' : '3'))

// 电子签约服务协议弹框
const FDDElectronicSigningService = () => {
  setTimeout(() => {
    if (signList.value.length > 0 && (!LStorage('isAgreePrivacy') || LStorage('isAgreePrivacy') === 'undefiend')) {
      showPrivacy.value = true
    }
  }, 100)
}
// watch(
//     () => waitState.value,
//     () => {
//       if (status.value === 'wait' && waitState.value === 'studio') {
//         FDDElectronicSigningService()
//       }
//     },
// )

// 已签约状态
const signStatus = {
  1: { color: '#ff8002', label: '审核中' },
  2: { color: '#37ca74', label: '生效中' },
  // 3: { color: '#cc463d', label: '被驳回' },
  4: { color: '#6a6a6c', label: '已取消' },
}

// 获取数据
const signList = ref(<IObjArray>[])

// 预览
const view = async (contractPath: string) => {
  storeCommit('contractPath', contractPath)
  Router.push('webviewPreview')
}
// 签约
const sign = async (signId: string) => {
  await MsgLoading()
  const { code, data } = await signContract({ signId }).finally(() => MsgLoadingClear())
  if (code === 200) {
    storeCommit('contractPath', data)
    Router.push('webviewPreview')
  }
}
// 电子合同签约服务 弹框
const showPrivacy = ref(false)
const aloneChecked1 = ref(false)
const aloneChecked2 = ref(false)
const cancelPop = () => {
  showPrivacy.value = false
  setTimeout(() => {
    aloneChecked1.value = false
    aloneChecked2.value = false
    showPrivacy.value = true
  }, 300)
}
const agPop = async () => {
  if (aloneChecked1.value && aloneChecked2.value) {
    LStorage('isAgreePrivacy', true)
    showPrivacy.value = false
  }
}

const changePrivacy1 = async (ean: any) => {
  aloneChecked1.value = ean
}
const changePrivacy2 = async (ean: any) => {
  aloneChecked2.value = ean
}
</script>

<style lang="less" scoped>
.wrap {
  display: flex;
  flex-direction: column;
  .sign_box {
    background: #FFFFFF;
    margin: 30rpx 40rpx;
    border-radius: 24rpx;
    .contractNo {
      padding: 0 40rpx;
      height: 80rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .color {
        opacity: .45;
      }
    }
    .reject_reason {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      padding: 18rpx 40rpx 20rpx;
      .color {
        opacity: .45;
      }
    }
    .contractName {
      width: 90%;
      height: 120rpx;
      border-bottom:1px solid rgba(0,0,0,.05);
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .handle {
      width: calc(100% - 80rpx);
      margin: auto;
      padding: 28rpx 0;
      border-top: solid 1rpx #e5e5e5;
    }
  }
  .list {
    flex: 1 1;
  }
}
.pricacyPop {
  width: 100vw;
  padding: 0 20rpx;
  .title {
    font-size: 36rpx;
    font-weight: bolder;
    text-align: center;
    margin-top: 28rpx;
    margin-bottom: 28rpx;
  }
  .tips {
    width: 100%;
    font-size: 28rpx;
    padding-left: 5%;
    padding-right: 5%;
    margin-bottom: 32rpx;
  }
  .options {
    width: 100%;
    padding-left: 5%;
    padding-right: 5%;
    .firstPrav {
      width: 100%;
      display: flex;
      align-items: flex-start;
      margin-bottom: 20rpx;
      .rightItem {
        width: 90%;
        font-size: 28rpx;
        .fchkb {
          .schkb {
            color: #1890FF;
            word-break: break-all;
          }
        }
      }
    }
    .secondPrav {
      width: 100%;
      font-size: 28rpx;
      display: flex;
      .rightInfo {
        height: 56rpx;
        line-height: 56rpx;
      }
    }
  }
  .line {
    width: 100%;
    height: 1px;
    margin-top: 52rpx;
    background-color: rgba(192, 192, 192, .5);
  }
  .foot {
    width: 100%;
    display: flex;
    justify-content: space-around;
    margin-top: 36rpx;
    margin-bottom: 8rpx;
    font-size: 36rpx;
  }
}
</style>
